﻿using HECore.ServiceFrame.Models;
using HECore.ServiceFrame.Redis;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;

namespace HECore.ServiceFrame.Attributes
{
    /// <summary>
    /// 账号鉴权
    /// </summary>
    public class AccountAuthorizeAttribute : TypeFilterAttribute
    {
        /// <summary>
        /// 账号鉴权
        /// </summary>
        public AccountAuthorizeAttribute() : base(typeof(AccountAuthorizeFilter)) { }
    }

    /// <summary>
    /// 账号鉴权
    /// </summary>
    public class AccountAuthorizeFilter : IAuthorizationFilter
    {
        private readonly FrameRedisClient _redisClient;
        private readonly CurrentAccount _currentAccount;

        /// <summary>
        /// 依赖注入
        /// </summary>
        public AccountAuthorizeFilter(FrameRedisClient redisClient, CurrentAccount currentAccount)
        {
            _redisClient = redisClient;
            _currentAccount = currentAccount;
        }

        /// <summary>
        /// 验证权限
        /// </summary>
        /// <param name="context"></param>
        public async void OnAuthorization(AuthorizationFilterContext context)
        {
            var Headers = context.HttpContext.Request.Headers;
            if (Headers.ContainsKey("token"))
            {
                var token = Headers["token"].ToString();
                if (string.IsNullOrEmpty(token))
                {
                    //未授权，需要登录
                    context.Result = new ContentResult
                    {
                        StatusCode = (int)HttpStatusCode.Unauthorized,
                        ContentType = "application/json;charset=utf-8",
                        Content = JsonConvert.SerializeObject(new ResultContent
                        {
                            Status = (int)HttpStatusCode.Unauthorized,
                            Code = "token.invalid",
                            Title = "登录已失效,请重新登录",
                            Describe = "未传递登录凭证"
                        })
                    };
                }
                else
                {
                    var isExisTokenKey = await _redisClient.KeyExistsAsync($"account:login:token:{token}");
                    if (isExisTokenKey)
                    {
                        // 获取并设置当前登录员工信息
                        var LoginAccount = await _redisClient.StringGetAsync(token);
                        var currentAccount = JsonConvert.DeserializeObject<CurrentAccount>(LoginAccount);
                        _currentAccount.AccountId = currentAccount.AccountId;
                    }
                    else
                    {
                        //无效的token
                        context.Result = new ContentResult
                        {
                            StatusCode = (int)HttpStatusCode.Unauthorized,
                            ContentType = "application/json;charset=utf-8",
                            Content = JsonConvert.SerializeObject(new ResultContent
                            {
                                Status = (int)HttpStatusCode.Unauthorized,
                                Code = "token.invalid",
                                Title = "登录已失效,请重新登录",
                                Describe = "无效的登录凭证"
                            })
                        };
                    }
                }
            }
            else
            {
                //未授权，需要登录
                context.Result = new ContentResult
                {
                    StatusCode = (int)HttpStatusCode.Unauthorized,
                    ContentType = "application/json;charset=utf-8",
                    Content = JsonConvert.SerializeObject(new ResultContent
                    {
                        Status = (int)HttpStatusCode.Unauthorized,
                        Code = "token.invalid",
                        Title = "登录已失效,请重新登录",
                        Describe = "未传递登录凭证"
                    })
                };
            }
        }
    }
}